package com.dly.blog.controller;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.asymmetric.Sign;
import com.dly.blog.annotation.OpLog;
import com.dly.blog.content.RedisContent;
import com.dly.blog.domain.vo.SignVO;
import com.dly.blog.domain.vo.UserVO;
import com.dly.blog.msg.R;
import com.dly.blog.utile.RedisUtils;
import com.dly.blog.utile.SecurityUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jodd.util.StringPool;
import lombok.AllArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Date;

@RestController
@RequestMapping("/sign")
@AllArgsConstructor
@Tag(name="签到相关")
@OpLog("签到相关")
public class SignController extends BaseController {

    private final RedisUtils redisUtils;

    @GetMapping("/on")
    @Operation(summary = "签到")
    public ResponseEntity<R<Void>> sign(){
        LocalDateTime now = LocalDateTime.now();
        String format = DateUtil.format(now, "yyyyMM");
        //获取今天的
        int dayOfMonth = now.getDayOfMonth();
        redisUtils.setBitMap(RedisContent.SIGN + SecurityUtils.getUserId()+ StringPool.COLON + format, dayOfMonth, true);
        return operate(this::success);
    }

    @GetMapping("/info")
    @Operation(summary = "签到情况")
    public ResponseEntity<R<SignVO>> getSign(String day){
        LocalDate now = LocalDate.now();
        if(StrUtil.isBlank(day)){
            day = DateUtil.format(new Date(), "yyyyMM");
        }
        int dayOfMonth = now.getDayOfMonth();
        String key = RedisContent.SIGN + SecurityUtils.getUserId()+ StringPool.COLON + day;
        SignVO signVO = new SignVO();
        signVO.setSign(redisUtils.getBitMap(key, dayOfMonth));
        signVO.setSignCount(redisUtils.countSign(key, now.lengthOfMonth(), dayOfMonth));
        signVO.setSignStatus(tobBitString(redisUtils.getAllBitMap(key)));
        return operate(()-> successDate(signVO));
    }

    private String tobBitString(Long value){
        String binaryString = Long.toBinaryString(value);
        int length = binaryString.length();
        StringBuilder stringBuilder = new StringBuilder();
        if(length < 32){
            stringBuilder.append("0".repeat(32 - binaryString.length()));
        }
        stringBuilder.append(binaryString);
        return stringBuilder.toString();
    }
}
